//
//  ALEmoticonKeyboard.swift
//  键盘-表情处理
//
//  Created by Miaoyang on 16/4/19.
//  Copyright © 2016年 Miaoyang. All rights reserved.
//

import UIKit

/// 自定义的表情键盘
class ALEmoticonKeyboard: UIView {
    
    private let ReuseIdentifier = "ReuseIdentifier"
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        super.init(frame: newFrame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        backgroundColor = UIColor.brownColor()
        
        // 添加控件
        addSubview(collectionView)
        addSubview(emoticonToolBar)
        
        // 添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        emoticonToolBar.translatesAutoresizingMaskIntoConstraints = false
        
        // VFL
        // collectionView 水平,左右和父控件重合
        // H: 水平 V: 垂直
        // ||, |:父控件左边/顶部   |:父控件右边/底部
        // [cv]: 表示一个view  [:view的左边  ]: view的右边
        // views: VFL里面用到的view映射
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: ["cv" : collectionView]))
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: ["tb" : emoticonToolBar]))
        
        // 垂直方向,
        // collectionView的顶部到父控件顶部0
        // collectioView的底部和emoticonToolBar的顶部重合
        // emoticonToolBar高度44
        // emoticonToolBar的底部和父控件的底部重合
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: [], metrics: nil, views: ["cv" : collectionView, "tb": emoticonToolBar]))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 子控件的大小就确定了
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.frame.size
    }
    
    // MARK: - 懒加载
    /// collectionView
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        // 设置
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        cv.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        cv.bounces = false
        
        cv.dataSource = self
        cv.delegate = self
        
        cv.registerClass(ALEmoticonKeyBoardPgeCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        
        return cv
    }()
    
    /// toolBar
    private lazy var emoticonToolBar: ALEmoticonToolBar = {
        let toolBar = ALEmoticonToolBar.emoticonToolBar()
        
        // 5.设置self为代理
        toolBar.delegate = self
        
        return toolBar
    }()
    
    // collectionView模拟的组和cell数量
    private let items = [1, 6, 4, 2]
}

// 6.实现代理协议
extension ALEmoticonKeyboard: ALEmoticonToolBarDelegate {
    /// 7.实现代理协议的方法.按钮点击
    func emoticonToolBar(toolBar: ALEmoticonToolBar, selectedButtonType type: ALEmoticonToolBarType) {
        print("我再HMEmoticonKeyboard知道按钮被点击了,切换collectionView: \(type)")
        // 滚动到对应的组
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
}

extension ALEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    // 有多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return items.count
    }
    
    // 每组有几个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items[section]
    }
    
    // cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! ALEmoticonKeyBoardPgeCell
        
        cell.backgroundColor = UIColor.randomColor()
        cell.indexPath = indexPath
        
        return cell
    }
    
    // scrollView滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 判断显示哪一组
        
        var refPoint = scrollView.center
        refPoint.x += scrollView.contentOffset.x
        //        print("refPoint: \(refPoint)")
        
        // 获取正在显示的cell
        for cell in collectionView.visibleCells() {
            if cell.frame.contains(refPoint) {
                // 获取cell的indexPath
                let indexPath = collectionView.indexPathForCell(cell)
                //
                // 选中对应这组的按钮
//                  emoticonToolBar.switchSelectorButton(indexPath!.section)
                emoticonToolBar.switchSelectButton(indexPath!.section)
            }
            
        }
    }
}